﻿using BusinessLayer.DatabaseEntities;
using BusinessLayer.VDataEntities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BusinessLayer
{
    public class ReportBusiness
    {

        public static long AddImages(byte[] image, long reportID)
        {
            using (TrialManagementEntities entity = new TrialManagementEntities())
            {
                Image imageEntity = new Image();
                imageEntity.Image1 = image;
                imageEntity.IsActive = true;
                imageEntity.UploadDate = DateTime.Now;
                imageEntity.ReportInfoID = reportID;
                entity.Image.Add(imageEntity);
                entity.SaveChanges();
                return imageEntity.ID;
            }
        }

        public static void DeleteImage(long imageID)
        {
            using (TrialManagementEntities entities = new TrialManagementEntities())
            {
                var imageEntity = (from image in entities.Image
                                   where image.ID == imageID
                                   select image).FirstOrDefault();
                if (imageEntity != null)
                {
                    imageEntity.IsActive = false;
                    entities.SaveChanges();
                }
            }
        }

        public static void UpdateReports(long reportID, string comments, VInputData[] updatedInputs)
        {
            using (TrialManagementEntities entity = new TrialManagementEntities())
            {
                var report = (from r in entity.ReportInfo
                              where r.ID == reportID
                              select r).FirstOrDefault();
                if (report != null)
                {
                    report.IsActive = true;
                    //report.Comments = comments;
                    List<ReportInputData> inputDataList = (from input in entity.ReportInputData
                                                           where input.ReportInfoID == reportID
                                                           select input).ToList();
                    foreach (var updatedInput in updatedInputs)
                    {
                        var needUpdatedInput = inputDataList.Find(p => p.ID == updatedInput.ID);
                        if (needUpdatedInput != null)
                        {
                            needUpdatedInput.Value = updatedInput.Value;
                        }
                    }
                    entity.SaveChanges();
                }
            }
        }

        public static VReport GetBasicReportInfo(long ID)
        {
            using (TrialManagementEntities entities = new TrialManagementEntities())
            {
                VReport vreport = new VReport();
                Report report = entities.Report.Where(p => p.ID == ID).FirstOrDefault();
                if (report != null)
                {
                    vreport = new VReport() { ID = report.ID, Name = report.Name, CreatedDate = report.CreateTime };
                }
                return vreport;
            }
        }

        public static VReport GetByID(long id)
        {
            using (TrialManagementEntities entities = new TrialManagementEntities())
            {
                ReportInfo reportInfo = entities.ReportInfo.Where(p => p.ID == id).FirstOrDefault();
                if (reportInfo != null)
                {
                    VReport vreport = new VReport() { ID = reportInfo.ID, CreatedDate = reportInfo.CreateDate, ReportID = reportInfo.ReportID, IsObserve = reportInfo.IsObserveInfo, headTitle = reportInfo.IsObserveInfo == true ? "调查信息" : "用药信息" };
                    var imageList = from image in entities.Image
                                    where image.ReportInfoID == id && image.IsActive == true
                                    select new VImage() { ID = image.ID, Image = image.Image1, UploadDate = image.UploadDate };
                    vreport.Images = imageList.ToArray();

                    var inputFields = from inputData in entities.ReportInputData
                                      join inputField in entities.ReportlInputField
                                      on inputData.ReportInputFieldID equals inputField.ID
                                      where inputData.ReportInfoID == id
                                      select new VInputData() { ID = inputData.ID, DataType = inputField.DataType, Name = inputField.Name, Value = inputData.Value, FieldID = inputField.ID, IsMandary = inputData.IsMandary };
                    vreport.inputFields = inputFields.ToArray();

                    long trialSiteID = (from report in entities.Report
                                        where report.ID == reportInfo.ReportID
                                        select report.TrialSiteID).FirstOrDefault();

                    var trialSite = (from ts in entities.TrialSite
                                     where ts.ID == trialSiteID
                                     select ts).FirstOrDefault();
                    var trial = (from t in entities.Trial
                                 where t.ID == trialSite.TrialID
                                 select t).FirstOrDefault();
                    vreport.Name = (from report in entities.Report
                                    where report.ID == reportInfo.ReportID
                                    select report.Name).FirstOrDefault();
                    vreport.TrialSiteID = trialSiteID;
                    vreport.TrialID = trialSite.TrialID;
                    vreport.trialSite = trialSite;
                    vreport.TrialGuideID = trial.TrialGuideID.HasValue ? trial.TrialGuideID.Value : 0;
                    return vreport;
                }

                throw new Exception(string.Format("No report was found with ID {0}", id));
            }
        }

        /// <summary>
        /// key is the input filed id
        /// 
        /// </summary>
        /// <returns></returns>
        public static Dictionary<long, List<VItem>> GetAllFieldsDataSource()
        {
            using (TrialManagementEntities entities = new TrialManagementEntities())
            {
                var dataList = entities.ReportInputFieldDataSource.ToArray();
                Dictionary<long, List<VItem>> dictionary = new Dictionary<long, List<VItem>>();

                foreach (var data in dataList)
                {
                    //if (dictionary.Keys.Contains(data.ReportInputFieldID))
                    //{
                    if (dictionary.ContainsKey(data.ReportInputFieldID))
                    {
                        dictionary[data.ReportInputFieldID].Add(new VItem() { ID = data.ID, Description = data.Description, Value = data.Value });
                    }
                    else
                    {
                        List<VItem> itemList = new List<VItem>();
                        itemList.Add(new VItem() { ID = data.ID, Value = data.Value, Description = data.Description });
                        dictionary.Add(data.ReportInputFieldID, itemList);
                    }
                    //}
                }

                return dictionary;
            }
        }

        public static long CreateNewProcess(VDataEntity data)
        {
            using (TrialManagementEntities entities = new TrialManagementEntities())
            {
                Report info = new Report();
                info.TrialSiteID = data.ID;
                info.Name = string.Format("处理{0}:{1}", GetAllReportProcess(data.ID).Count() + 1, data.Name);
                info.CreateTime = DateTime.Now;
                info.IsActive = true;
                entities.Report.Add(info);
                entities.SaveChanges();
                return info.ID;
            }
        }

        public static VDataEntity[] GetAllReportProcess(long trialSiteID)
        {
            using (TrialManagementEntities entities = new TrialManagementEntities())
            {
                var list = from report in entities.Report
                           where report.TrialSiteID == trialSiteID && report.IsActive == true
                           select new VDataEntity { ID = report.ID, Name = report.Name };
                return list.ToArray();
            }
        }

        /// <summary>
        /// 调查信息根据观察时间排序
        /// 用药信息根据用药时间排序
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isObserve"></param>
        /// <returns></returns>
        public static List<VReportInfo> GetProcessInfoByProcessID(long id, bool isObserve)
        {
            using (TrialManagementEntities entities = new TrialManagementEntities())
            {
                long searchid;
                if (isObserve == true)
                {
                    searchid = (from repotinputfield in entities.ReportlInputField
                                where repotinputfield.Name == "观察时间"
                                select repotinputfield.ID).FirstOrDefault();
                }
                else
                {
                    searchid = (from repotinputfield in entities.ReportlInputField
                                where repotinputfield.Name == "用药时间"
                                select repotinputfield.ID).FirstOrDefault();
                }
                var list = from report in entities.ReportInfo
                           join reportinput in entities.ReportInputData on report.ID equals reportinput.ReportInfoID
                           where report.ReportID == id && report.IsActive == true && report.IsObserveInfo == isObserve
                           && reportinput.ReportInputFieldID == searchid
                           select new VReportInfo { ID = report.ID, IsObserveInfo = report.IsObserveInfo, ProcessDate = reportinput.Value };
                return list.OrderBy(c => c.ProcessDate).ToList();
            }
        }

        public static long CreateNewReport(long ID, bool isObserve, bool autoImport)
        {
            using (TrialManagementEntities entities = new TrialManagementEntities())
            {
                List<ReportInputData> reportinfo = new List<ReportInputData>();
                //自动赋用药信息
                if (autoImport == true)
                {
                    //查找上一次用药信息数据
                    var reportinfoId = (from ri in entities.ReportInfo
                                        where ri.ReportID == ID && ri.IsActive == true && ri.IsObserveInfo == isObserve
                                        select ri)
                        .OrderByDescending(c => c.CreateDate).FirstOrDefault().ID;
                    reportinfo = (from riData in entities.ReportInputData where riData.ReportInfoID == reportinfoId select riData).ToList();
                }

                //create report
                ReportInfo report = new ReportInfo();
                report.ReportID = ID;
                //save report update to active
                report.IsActive = false;
                report.IsObserveInfo = isObserve;
                report.CreateDate = DateTime.Now;
                entities.ReportInfo.Add(report);
                entities.SaveChanges();

                long reportInfoID = report.ID;
                //input the fields need to be fill in the report
                long trialSiteID = (from reportentity in entities.Report
                                    where reportentity.ID == ID
                                    select reportentity.TrialSiteID)
                                    .FirstOrDefault();
                long trialID = (from trialSiteentity in entities.TrialSite
                                where trialSiteentity.ID == trialSiteID
                                select trialSiteentity.TrialID)
                                    .FirstOrDefault();

                long productCategoryID = (from product in entities.Product
                                          join trial in entities.Trial
                                          on product.ID equals trial.ProductID
                                          where trial.ID == trialID
                                          select product.CategoryID).FirstOrDefault();

                var fields = (from r in entities.RProductCategoryReportInputField
                              join reportInputField in entities.ReportlInputField
                              on r.ReportInputFieldID equals reportInputField.ID
                              where r.ProductCategoryID == productCategoryID
                              && (isObserve == true ? reportInputField.IsObserve == 1 : reportInputField.IsObserve == 0)
                              select new { fieldID = r.ReportInputFieldID, IsMandary = r.IsManadary, sortOrder = r.SortSeq }).ToArray().OrderBy(c => c.sortOrder);
                foreach (var field in fields)
                {
                    ReportInputData inputData = new ReportInputData();
                    inputData.IsMandary = field.IsMandary;
                    inputData.ReportInfoID = reportInfoID;
                    inputData.ReportInputFieldID = field.fieldID;
                    inputData.Value = reportinfo.Find(r => r.ReportInputFieldID == field.fieldID) != null == true ? reportinfo.Find(r => r.ReportInputFieldID == field.fieldID).Value : "";
                    entities.ReportInputData.Add(inputData);
                }
                entities.SaveChanges();


                return reportInfoID;
            }
        }

        public static VReportBasicInfo GetProcessBasicInfo(long processID)
        {
            using (TrialManagementEntities entities = new TrialManagementEntities())
            {
                var reportenties = (from report in entities.Report
                                    where report.ID == processID
                                    select report).FirstOrDefault();
                var trialSite = (from ts in entities.TrialSite
                                 where ts.ID == reportenties.TrialSiteID
                                 select new { ID = ts.ID, TrialID = ts.TrialID, Name = reportenties.Name, Status = ts.Status.HasValue ? ts.Status.Value : 1 }).FirstOrDefault();
                var trial = (from t in entities.Trial
                             where t.ID == trialSite.TrialID
                             select new VReportBasicInfo { ID = processID, Name = reportenties.Name, TrialSiteID = trialSite.ID, Status = trialSite.Status, TrialGuideID = t.TrialGuideID.HasValue == true ? t.TrialGuideID.Value : 0 }).FirstOrDefault();
                return trial;

            }
        }

        public static Dictionary<long, List<VReportInfo>> GetAllInputDataFieldByTrialSiteID(long trialSiteID)
        {
            using (TrialManagementEntities entities = new TrialManagementEntities())
            {
                var data = from report in entities.Report
                           join reportinfo in entities.ReportInfo on report.ID equals reportinfo.ReportID
                           where report.TrialSiteID == trialSiteID && reportinfo.IsActive == true
                           select new { isObserve = reportinfo.IsObserveInfo, ReportID = report.ID, ReportInfoID = reportinfo.ID };
                Dictionary<long, List<VReportInfo>> result = new Dictionary<long, List<VReportInfo>>();
                foreach (var item in data)
                {
                    List<VReportInfo> temp = GetProcessInfoByProcessID(item.ReportID, item.isObserve);
                    result.Add(item.ReportInfoID, temp);
                }
                return result;
            }
        }

        public static List<ReportInfo> GetAllDataByReportID(long id)
        {
            using (TrialManagementEntities entities = new TrialManagementEntities())
            {
                var reportInfoArray = (from reportInfo in entities.ReportInfo
                                       where reportInfo.ReportID == id && reportInfo.IsActive == true
                                       select new ReportInfo { ID = reportInfo.ID, CreateDate = reportInfo.CreateDate, IsObserveInfo = reportInfo.IsActive }).ToList();
                return reportInfoArray;
            }
        }

        public static void CopyAllYongyaoInfo(long trialSiteID,long newReportID )
        {
            using (TrialManagementEntities entities = new TrialManagementEntities())
            {
                //获取第一次处理ID
                var reportID = (from report in entities.Report
                                where report.TrialSiteID == trialSiteID && report.IsActive == true
                                select report.ID).FirstOrDefault();
                //获取第一次处理的所有用药信息的ID
                var reportInfoId = (from reportInfo in entities.ReportInfo
                                    where reportInfo.ReportID == reportID && reportInfo.IsActive == true && reportInfo.IsObserveInfo == false
                                    select reportInfo.ID);
                //复制用药信息给新增加的处理
                var allData = (from reportInputData in entities.ReportInputData
                               where reportInfoId.Contains(reportInputData.ReportInfoID) group reportInputData by reportInputData.ReportInfoID into g
                               select g);
                foreach (var item in allData)
                {
                    ////create report
                    //ReportInfo report = new ReportInfo();
                    //report.ReportID = newReportID;
                    ////save report update to active
                    //report.IsActive = false;
                    //report.IsObserveInfo = false;
                    //report.CreateDate = DateTime.Now;
                    //entities.ReportInfo.Add(report);
                    //entities.SaveChanges();
                }
            }
        }
    }
}
